﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace 激光与气象仪界面集成//代码写的太乱，实在对不起。我应该先规划好再敲，这个原型写出来就讲究着用把，需要优化再重新组合，哈哈!C_博
{
    public partial class Form1 : Form
    {
        public SerialPort serial1 = new SerialPort();//新建一个串口类
        public SerialPort serial2 = new SerialPort();//新建一个串口类
        bool isRUN = false;//串口状况
        public Bitmap bitmp_1;//指针盘1
        public Bitmap bm_1;//指针
        public Bitmap bitmp_2;//指针盘2
        public Bitmap bm_2;
        public double WindSpeed_1, WindSpeed_2;//风速1 风速2
        public int WindDirection_1, WindDirection_2;//风向1 风向2

        public class CustomComparer : System.Collections.IComparer
        {
            public int Compare(object x, object y)//比较两个字符串的长度
            {
                string s1 = (string)x;
                string s2 = (string)y;

                if (s1.Length > s2.Length) return 1;
                if (s1.Length < s2.Length) return -1;
                return s1.CompareTo(s2);
            }
        }
        public Form1()
        {
            InitializeComponent();
            txtPath.Text = System.AppDomain.CurrentDomain.BaseDirectory +"激光测距和微气象仪历史数据\\";//程序一开机，确定历史数据的位置
            comboBox1.Items[0]= Properties.Settings.Default.LaserCOMPort;//一开机导入上次的串口配置
            comboBox2.Items[0] = Properties.Settings.Default.WeaCOMPort;

            textBox9.Text = Properties.Settings.Default.distance1;
            textBox11.Text =Properties.Settings.Default.distance2 ;
            textBox12.Text =Properties.Settings.Default.distance3 ;
            textBox13.Text =Properties.Settings.Default.distance4 ;

            chart1.ChartAreas[0].AxisY.Minimum = 0;//设置chart的显示范围
            chart1.ChartAreas[0].AxisY.Maximum = 310;
        }

        //重绘旋转后的仪表盘图片 
        public void Overlap_1(Bitmap btm, int x, int y, int w, int h)
        {
            Bitmap image = new Bitmap(btm);
            Bitmap hi = new Bitmap(bm_1);
            Graphics g = Graphics.FromImage(hi);
            g.DrawImage(image, new Rectangle(x, y, w, h));
            bm_1 = hi;
        }
        public void Overlap_2(Bitmap btm, int x, int y, int w, int h)
        {
            Bitmap image = new Bitmap(btm);
            Bitmap hi = new Bitmap(bm_2);
            Graphics g = Graphics.FromImage(hi);
            g.DrawImage(image, new Rectangle(x, y, w, h));
            bm_2 = hi;
        }
        //-------------------磁罗盘显示函数-------------------//
        //入口参数：
        //航向角 dir_angle 范围0~360 度 
        private void Compass_Disp_1(double dir_angle)
        {
            string file = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"point.jpg");
            bitmp_1 = new Bitmap(file);
            Bitmap pointImage = new Bitmap(250, 250);
            System.Drawing.Graphics gPoint = System.Drawing.Graphics.FromImage(pointImage);
            gPoint.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            gPoint.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量
            Rectangle rectPoint = new Rectangle(0, 0, 250, 250);
            gPoint.TranslateTransform(125, 125);
            //g.RotateTransform(360 - row_angle);
            gPoint.RotateTransform((float)dir_angle);
            //恢复图像在水平和垂直方向的平移 
            gPoint.TranslateTransform(-125, -125);
            gPoint.DrawImage(bitmp_1, rectPoint);
            //重至绘图的所有变换  
            gPoint.ResetTransform();
            gPoint.Dispose();
            //保存旋转后的图片
            bm_1 = pointImage;
            Overlap_1(pointImage, 0, 0, 250, 250);
            CompointBox.Image = bm_1;

            // 刻度盘截圆
            System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
            gp.FillMode = 0;
            gp.AddEllipse(new Rectangle(0, 0, 350, 350));
            ComshellBox.Region = new Region(gp);
            //表盘截圆
            System.Drawing.Drawing2D.GraphicsPath gp1 = new System.Drawing.Drawing2D.GraphicsPath();
            gp1.FillMode = 0;
            gp1.AddEllipse(new Rectangle(0, 0, 250, 250));
            CompointBox.Region = new Region(gp1);
            gp1.Dispose();
            gp.Dispose();
            gPoint.Dispose();
            bitmp_1.Dispose();
            //Graphics gp1 = CompointBox.CreateGraphics();
            //gp1.DrawEllipse()
        }
        private void Compass_Disp_2(double dir_angle)
        {
            string file = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"point.jpg");
            bitmp_2 = new Bitmap(file);
            Bitmap pointImage = new Bitmap(250, 250);
            System.Drawing.Graphics gPoint = System.Drawing.Graphics.FromImage(pointImage);
            gPoint.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            gPoint.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量
            Rectangle rectPoint = new Rectangle(0, 0, 250, 250);
            gPoint.TranslateTransform(125, 125);
            //g.RotateTransform(360 - row_angle);
            gPoint.RotateTransform((float)dir_angle);
            //恢复图像在水平和垂直方向的平移 
            gPoint.TranslateTransform(-125, -125);
            gPoint.DrawImage(bitmp_2, rectPoint);
            //重至绘图的所有变换  
            gPoint.ResetTransform();
            gPoint.Dispose();
            //保存旋转后的图片
            bm_2 = pointImage;
            Overlap_2(pointImage, 0, 0, 250, 250);
            pictureBox2.Image = bm_2;

            // 刻度盘截圆
            System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
            gp.FillMode = 0;
            gp.AddEllipse(new Rectangle(0, 0, 350, 350));
            pictureBox1.Region = new Region(gp);
            //表盘截圆
            System.Drawing.Drawing2D.GraphicsPath gp1 = new System.Drawing.Drawing2D.GraphicsPath();
            gp1.FillMode = 0;
            gp1.AddEllipse(new Rectangle(0, 0, 250, 250));
            pictureBox2.Region = new Region(gp1);
            gp1.Dispose();
            gp.Dispose();
            gPoint.Dispose();
            bitmp_2.Dispose();
            //Graphics gp1 = CompointBox.CreateGraphics();
            //gp1.DrawEllipse()
        }
        public void serial1_send_data(byte[] buffer)//串口1的发送数据函数，串口1将分配给激光测距传感器
        {
            if (buffer.Length > 0)
            {
                if (serial1.IsOpen)
                {
                    serial1.Write(buffer, 0, buffer.Length);

                }
            }
        }

        public void serial2_send_data(byte[] buffer)//串口2的发送数据函数，串口2将分配给微气象仪
        {
            if (buffer.Length > 0)
            {
                if (serial2.IsOpen)
                {
                    serial2.Write(buffer, 0, buffer.Length);

                }
            }
        }
        public static bool ReceDataIsTrue(byte[] Receive, int ReceiveNum)//判断激光测距传感器收到的帧是否为正确的
        {
            string R1, R2, R3, R4, R5, R6;
            int V1, V2, V3, V4, V5, V6;
            R1 = Convert.ToString(Receive[0], 16);
            R2 = Convert.ToString(Receive[1], 16);
            R3 = Convert.ToString(Receive[2], 16);
            R4 = Convert.ToString(Receive[3], 16);
            R5 = Convert.ToString(Receive[4], 16);
            R6 = Convert.ToString(Receive[5], 16);
            V1 = Convert.ToInt32(R1, 16);
            V2 = Convert.ToInt32(R2, 16);
            V3 = Convert.ToInt32(R3, 16);
            V4 = Convert.ToInt32(R4, 16);
            V5 = Convert.ToInt32(R5, 16);
            V6 = Convert.ToInt32(R6, 16);
            V1 = V1 - 128;
            if (V6 == (V1 ^ V2 ^ V3 ^ V4 ^ V5))
            {
                return true;
            }
            return false;
        }
        public static bool ReceModbusDataIsTrue(byte[] Receive, int ReceiveNum)//判断微气象仪收到的帧是否为正确的
        {
            byte[] NeedToMakeCRCdata = new byte[5] { 0x00, 0x00, 0x00, 0x00, 0x0 };//C8 03 02 01 56 E5 FA 
            NeedToMakeCRCdata[0] = Receive[0];
            NeedToMakeCRCdata[1] = Receive[1];
            NeedToMakeCRCdata[2] = Receive[2];
            NeedToMakeCRCdata[3] = Receive[3];
            NeedToMakeCRCdata[4] = Receive[4];
            byte[] CRCresult = new byte[2];
            CRCresult = CRC16.CRCCalc(NeedToMakeCRCdata);
            if ((CRCresult[0]== Receive[5])&&(CRCresult[1] == Receive[6]))
            {
                return true;
            }
            return false;
        }
        public static bool GoodTargetIsTrue(byte[] Receive, int ReceiveNum)//解析激光测距仪返回帧并判断激光测距的目标是否是个好目标
        {
            string R4;
            int V4;
            R4 = Convert.ToString(Receive[3], 16);
            V4 = Convert.ToInt32(R4, 16);
            if ((V4 & 0x40) == 0x40)
            {
                return true;
            }
            return false;
        }
        public static bool Q1IsTrue(byte[] Receive, int ReceiveNum)//解析激光测距仪返回帧并判断激光测距的目标是否太近了
        {
            string R5;
            int V5;
            R5 = Convert.ToString(Receive[4], 16);
            V5 = Convert.ToInt32(R5, 16);

            if ((V5 & 0x40) == 0x40)
            {
                return true;
            }
            return false;
        }
        public static Double ReceDataOfDistance(byte[] Receive, int ReceiveNum)//这个函数将激光测距仪的帧解析出来得到一个浮点的距离
        {
            string R4, R5;
            int V4, V5;
            double Distance, DistanceData;
            R4 = Convert.ToString(Receive[3], 16);
            R5 = Convert.ToString(Receive[4], 16);
            V4 = Convert.ToInt32(R4, 16);
            V5 = Convert.ToInt32(R5, 16);
            DistanceData = (V4 & 0x3F) * 64 + (V5 & 0x3F);
            Distance = (DistanceData - 5584.0000) / (-4095.0000 / 220.0000);
            return Distance;
        }
        private void ComshellBox_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (isRUN == false)
            {
                button1.Text = "停止通信";
                timer1.Enabled = true;
                timer2.Enabled = true;
                isRUN = true;

              
            }
            else
            {
               
                button1.Text = "开始通信";
                timer1.Enabled = false;
                timer2.Enabled = false;
                isRUN = false;
                serial1.Close();
                serial2.Close();
               
            }

            if (checkBox1.Checked == true)
            {
                try
                {
                    if (comboBox1.Text == "激光测距仪的串口")
                    {

                    }
                    else
                    {

                        serial1.PortName = comboBox1.Text;
                        serial1.BaudRate = int.Parse("38400");
                        serial1.Parity = Parity.None;
                        serial1.DataBits = int.Parse("8");
                        serial1.StopBits = StopBits.One;
                        serial1.Open();
                        //serial1_send_data(AskLaserDistance);

                    }
                }
                catch (Exception ex)
                {

                }
            }
            else {
                serial1.Close();
                textBox3.Text = "没选";
                textBox6.Text = "没选";
                textBox7.Text = "没选";
                textBox8.Text = "没选";
            }

            if (checkBox2.Checked == true)
            {
                try
                {
                    if (comboBox2.Text == "微气象仪的串口")
                    {
                    }
                    else
                    {
                        serial2.PortName = comboBox2.Text;
                        serial2.BaudRate = int.Parse("9600");
                        serial2.Parity = Parity.None;
                        serial2.DataBits = int.Parse("8");
                        serial2.StopBits = StopBits.One;
                        serial2.Open();
                    }

                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                serial2.Close();
                textBox1.Text = "没选";
                textBox2.Text = "没选";
                textBox4.Text = "没选";
                textBox5.Text = "没选";
            }


            if (checkBox1.Checked == true)
            {

                //激光测距的的串口初始化与使用
                byte[] AskLaserDistance_1 = new byte[] { 0x81, 0x04, 0x41, 0x44 };
                byte[] AskLaserDistance_2 = new byte[] { 0x82, 0x04, 0x41, 0x47 };
                byte[] AskLaserDistance_3 = new byte[] { 0x83, 0x04, 0x41, 0x46 };
                byte[] AskLaserDistance_4 = new byte[] { 0x84, 0x04, 0x41, 0x41 };
                bool ReceiDataIsTrue_1, Q1_1, GoodTarget_1, ReceiDataIsTrue_2, Q1_2, GoodTarget_2, ReceiDataIsTrue_3, Q1_3, GoodTarget_3, ReceiDataIsTrue_4, Q1_4, GoodTarget_4;
                double DistanceVale_1, DistanceVale_2, DistanceVale_3, DistanceVale_4;
                if (serial1.IsOpen)
                {
                    //serial1.DiscardOutBuffer();
                    //serial1.DiscardInBuffer();
                    serial1_send_data(AskLaserDistance_1);
                    System.Threading.Thread.Sleep(30);
                    int bytes_1 = serial1.BytesToRead;
                    byte[] Recbuffer_1 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_1 == 6)
                    {
                        try { serial1.Read(Recbuffer_1, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_1 = new byte[bytes_1];
                        serial1.Read(DiscardBuffer_1, 0, bytes_1);
                    }
                    ReceiDataIsTrue_1 = Form1.ReceDataIsTrue(Recbuffer_1, bytes_1);
                    GoodTarget_1 = Form1.GoodTargetIsTrue(Recbuffer_1, bytes_1);
                    Q1_1 = Form1.Q1IsTrue(Recbuffer_1, bytes_1);

                    if (ReceiDataIsTrue_1)
                    {
                        DistanceVale_1 = ReceDataOfDistance(Recbuffer_1, bytes_1);
                        label4.Text = Convert.ToString(GoodTarget_1);
                        label5.Text = Convert.ToString(Q1_1);
                        textBox3.Text = string.Format("{0:F2}", DistanceVale_1);
                        trackBar1.Value = (int)DistanceVale_1;
                    }
                    else
                    {
                        label4.Text = "null";
                        label5.Text = "null";
                        textBox3.Text = "null";

                    }


                    serial1_send_data(AskLaserDistance_2);
                    System.Threading.Thread.Sleep(30);
                    int bytes_2 = serial1.BytesToRead;
                    byte[] Recbuffer_2 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_2 == 6)
                    {
                        try { serial1.Read(Recbuffer_2, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_2 = new byte[bytes_2];
                        serial1.Read(DiscardBuffer_2, 0, bytes_2);
                    }
                    ReceiDataIsTrue_2 = Form1.ReceDataIsTrue(Recbuffer_2, bytes_2);
                    GoodTarget_2 = Form1.GoodTargetIsTrue(Recbuffer_2, bytes_2);
                    Q1_2 = Form1.Q1IsTrue(Recbuffer_2, bytes_2);

                    if (ReceiDataIsTrue_2)
                    {
                        DistanceVale_2 = ReceDataOfDistance(Recbuffer_2, bytes_2);
                        label21.Text = Convert.ToString(GoodTarget_2);
                        label24.Text = Convert.ToString(Q1_2);
                        textBox6.Text = string.Format("{0:F2}", DistanceVale_2);
                        trackBar2.Value = (int)DistanceVale_2;
                    }
                    else
                    {
                        label21.Text = "null";
                        label24.Text = "null";
                        textBox6.Text = "null";

                    }


                    serial1_send_data(AskLaserDistance_3);
                    System.Threading.Thread.Sleep(30);
                    int bytes_3 = serial1.BytesToRead;
                    byte[] Recbuffer_3 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_3 == 6)
                    {
                        try { serial1.Read(Recbuffer_3, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_3 = new byte[bytes_3];
                        serial1.Read(DiscardBuffer_3, 0, bytes_3);
                    }
                    ReceiDataIsTrue_3 = Form1.ReceDataIsTrue(Recbuffer_3, bytes_3);
                    GoodTarget_3 = Form1.GoodTargetIsTrue(Recbuffer_3, bytes_3);
                    Q1_3 = Form1.Q1IsTrue(Recbuffer_3, bytes_3);

                    if (ReceiDataIsTrue_3)
                    {
                        DistanceVale_3 = ReceDataOfDistance(Recbuffer_3, bytes_3);
                        label22.Text = Convert.ToString(GoodTarget_3);
                        label25.Text = Convert.ToString(Q1_3);
                        textBox7.Text = string.Format("{0:F2}", DistanceVale_3);
                        trackBar3.Value = (int)DistanceVale_3;
                    }
                    else
                    {
                        label22.Text = "null";
                        label25.Text = "null";
                        textBox7.Text = "null";

                    }


                    serial1_send_data(AskLaserDistance_4);
                    System.Threading.Thread.Sleep(30);
                    int bytes_4 = serial1.BytesToRead;
                    byte[] Recbuffer_4 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_4 == 6)
                    {
                        try { serial1.Read(Recbuffer_4, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_4 = new byte[bytes_4];
                        serial1.Read(DiscardBuffer_4, 0, bytes_4);
                    }
                    ReceiDataIsTrue_4 = Form1.ReceDataIsTrue(Recbuffer_4, bytes_4);
                    GoodTarget_4 = Form1.GoodTargetIsTrue(Recbuffer_4, bytes_4);
                    Q1_4 = Form1.Q1IsTrue(Recbuffer_4, bytes_4);

                    if (ReceiDataIsTrue_4)
                    {
                        DistanceVale_4 = ReceDataOfDistance(Recbuffer_4, bytes_4);
                        label23.Text = Convert.ToString(GoodTarget_4);
                        label26.Text = Convert.ToString(Q1_4);
                        textBox8.Text = string.Format("{0:F2}", DistanceVale_4);
                        trackBar4.Value = (int)DistanceVale_4;
                    }
                    else
                    {
                        label23.Text = "null";
                        label26.Text = "null";
                        textBox8.Text = "null";

                    }
                }
                else
                {

                }

            }


            if (checkBox2.Checked == true)
            {
                //微气象仪的串口初始化与使用
                byte[] AskWindSpeed_1 = new byte[] { 0xC8, 0x03, 0x00, 0x00, 0x00, 0x01, 0x95, 0x93 }; //C8 03 00 00 00 01 95 93
                byte[] AskWindDirection_1 = new byte[] { 0xC8, 0x03, 0x00, 0x01, 0x00, 0x01, 0xC4, 0x53 }; //C8 03 00 01 00 01 C4 53
                bool ReceiModbusDataIsTrue_1 = false;
                byte[] AskWindSpeed_2 = new byte[] { 0xC9, 0x03, 0x00, 0x00, 0x00, 0x01, 0x94, 0x42 }; //C8 03 00 00 00 01 95 93
                byte[] AskWindDirection_2 = new byte[] { 0xC9, 0x03, 0x00, 0x01, 0x00, 0x01, 0xC5, 0x82 }; //C8 03 00 01 00 01 C4 53
                bool ReceiModbusDataIsTrue_2 = false;

                if (serial2.IsOpen)
                {
                    // serial2.DiscardOutBuffer();
                    // serial2.DiscardInBuffer();
                    serial2_send_data(AskWindSpeed_1);
                    System.Threading.Thread.Sleep(30);
                    int bytes_1 = serial2.BytesToRead;
                    byte[] RecbufferWindSpeed_1 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_1 == 7)
                    {
                        try { serial2.Read(RecbufferWindSpeed_1, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_1 = new byte[bytes_1];
                        serial2.Read(DiscardBuffer_1, 0, bytes_1);
                    }
                    ReceiModbusDataIsTrue_1 = ReceModbusDataIsTrue(RecbufferWindSpeed_1, 7);
                    if (ReceiModbusDataIsTrue_1)
                    {
                        int WindSpeed100_1;
                        WindSpeed100_1 = (RecbufferWindSpeed_1[3] * 256 + RecbufferWindSpeed_1[4]);
                        WindSpeed_1 = WindSpeed100_1 * 0.01;
                        textBox1.Text = string.Format("{0:F2}", WindSpeed_1);
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_1 = false;
                    }

                    serial2_send_data(AskWindDirection_1);
                    System.Threading.Thread.Sleep(30);
                    bytes_1 = serial2.BytesToRead;
                    byte[] RecbufferWindDirection_1 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_1 == 7)
                    {
                        try { serial2.Read(RecbufferWindDirection_1, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_1 = new byte[bytes_1];
                        serial2.Read(DiscardBuffer_1, 0, bytes_1);
                    }
                    ReceiModbusDataIsTrue_1 = ReceModbusDataIsTrue(RecbufferWindDirection_1, 7);
                    if (ReceiModbusDataIsTrue_1)
                    {
                        WindDirection_1 = RecbufferWindDirection_1[3] * 256 + RecbufferWindDirection_1[4];
                        textBox2.Text = WindDirection_1.ToString();
                        Compass_Disp_1(WindDirection_1);
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_1 = false;
                    }


                    serial2_send_data(AskWindSpeed_2);
                    System.Threading.Thread.Sleep(30);
                    int bytes_2 = serial2.BytesToRead;
                    byte[] RecbufferWindSpeed_2 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_2 == 7)
                    {
                        try { serial2.Read(RecbufferWindSpeed_2, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_2 = new byte[bytes_2];
                        serial2.Read(DiscardBuffer_2, 0, bytes_2);
                    }
                    ReceiModbusDataIsTrue_2 = ReceModbusDataIsTrue(RecbufferWindSpeed_2, 7);
                    if (ReceiModbusDataIsTrue_2)
                    {
                        int WindSpeed100_2;
                        WindSpeed100_2 = (RecbufferWindSpeed_2[3] * 256 + RecbufferWindSpeed_2[4]);
                        WindSpeed_2 = WindSpeed100_2 * 0.01;
                        textBox4.Text = string.Format("{0:F2}", WindSpeed_2);
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_2 = false;
                    }

                    serial2_send_data(AskWindDirection_2);
                    System.Threading.Thread.Sleep(30);
                    bytes_2 = serial2.BytesToRead;
                    byte[] RecbufferWindDirection_2 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_2 == 7)
                    {
                        try { serial2.Read(RecbufferWindDirection_2, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_2 = new byte[bytes_2];
                        serial2.Read(DiscardBuffer_2, 0, bytes_2);
                    }
                    ReceiModbusDataIsTrue_2 = ReceModbusDataIsTrue(RecbufferWindDirection_2, 7);
                    if (ReceiModbusDataIsTrue_2)
                    {
                        WindDirection_2 = RecbufferWindDirection_2[3] * 256 + RecbufferWindDirection_2[4];
                        textBox5.Text = WindDirection_2.ToString();
                        Compass_Disp_2(WindDirection_2);
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_2 = false;
                    }
                }
                else
                {

                }



            }
        }
      
        
        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            string port_name_old = comboBox1.Text;

            string[] port_names = SerialPort.GetPortNames();
            Array.Sort(port_names, new CustomComparer());
            comboBox1.Items.Clear();
            comboBox1.Items.AddRange(port_names);
            comboBox1.Items.Add("不选");
          

            if ((comboBox1.Items.Count > 0) && (comboBox1.SelectedIndex < 0))
            {
                comboBox1.SelectedIndex = 0;
            }
              comboBox1.Text = port_name_old;
        }

        private void comboBox2_DropDown(object sender, EventArgs e)
        {

            string port_name_old = comboBox2.Text;

            string[] port_names = SerialPort.GetPortNames();
            Array.Sort(port_names, new CustomComparer());
            comboBox2.Items.Clear();
            comboBox2.Items.AddRange(port_names);
            comboBox2.Items.Add("不选");


            if ((comboBox2.Items.Count > 0) && (comboBox2.SelectedIndex < 0))
            {
                comboBox2.SelectedIndex = 0;
            }

            comboBox2.Text = port_name_old;
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        public int LaserSerialFramDataisErrnumber=0;
        public int WinderSerialFramDataisErrnumber = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            
            if ((LaserSerialFramDataisErrnumber>10)|| (WinderSerialFramDataisErrnumber > 10))
            {
                LaserSerialFramDataisErrnumber = 0;
                WinderSerialFramDataisErrnumber = 0;
                button1_Click(null, new EventArgs());
                MessageBox.Show("通讯错误超10次，485通讯已自动切断！");
            }
            else
            { 
            }
            
            double f1 = 0;
            double f2 = 0;
            double f3 = 0;
            double f4 = 0;

            if (checkBox1.Checked == true)
            {
                //激光测距的的串口初始化与使用
                byte[] AskLaserDistance_1 = new byte[] { 0x81, 0x04, 0x41, 0x44 };
                byte[] AskLaserDistance_2 = new byte[] { 0x82, 0x04, 0x41, 0x47 };
                byte[] AskLaserDistance_3 = new byte[] { 0x83, 0x04, 0x41, 0x46 };
                byte[] AskLaserDistance_4 = new byte[] { 0x84, 0x04, 0x41, 0x41 };
                bool ReceiDataIsTrue_1, ReceiDataIsTrue_2, ReceiDataIsTrue_3, ReceiDataIsTrue_4, Q1_1, Q1_2, Q1_3, Q1_4, GoodTarget_1, GoodTarget_2, GoodTarget_3, GoodTarget_4;
                double DistanceVale_1, DistanceVale_2, DistanceVale_3, DistanceVale_4;
                if (serial1.IsOpen)
                {
                    //serial1.DiscardOutBuffer();
                    //serial1.DiscardInBuffer();
                    serial1_send_data(AskLaserDistance_1);
                    System.Threading.Thread.Sleep(30);
                    int bytes_1 = serial1.BytesToRead;
                    byte[] Recbuffer_1 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_1 == 6)
                    {
                        try { serial1.Read(Recbuffer_1, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_1 = new byte[bytes_1];
                        serial1.Read(DiscardBuffer_1, 0, bytes_1);
                    }
                    ReceiDataIsTrue_1 = Form1.ReceDataIsTrue(Recbuffer_1, bytes_1);
                    GoodTarget_1 = Form1.GoodTargetIsTrue(Recbuffer_1, bytes_1);
                    Q1_1 = Form1.Q1IsTrue(Recbuffer_1, bytes_1);

                    if (ReceiDataIsTrue_1)
                    {
                        DistanceVale_1 = ReceDataOfDistance(Recbuffer_1, bytes_1);
                        label4.Text = Convert.ToString(GoodTarget_1);
                        label5.Text = Convert.ToString(Q1_1);
                        textBox3.Text = string.Format("{0:F2}", DistanceVale_1);
                        trackBar1.Value = (int)DistanceVale_1;
                        f1 = (double)DistanceVale_1;

                    }
                    else
                    {
                        label4.Text = "null";
                        label5.Text = "null";
                        textBox3.Text = "null";
                        LaserSerialFramDataisErrnumber++;//该帧错误累加1
                    }

                    serial1_send_data(AskLaserDistance_2);
                    System.Threading.Thread.Sleep(30);
                    int bytes_2 = serial1.BytesToRead;
                    byte[] Recbuffer_2 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_2 == 6)
                    {
                        try { serial1.Read(Recbuffer_2, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_2 = new byte[bytes_2];
                        serial1.Read(DiscardBuffer_2, 0, bytes_2);
                    }
                    ReceiDataIsTrue_2 = Form1.ReceDataIsTrue(Recbuffer_2, bytes_2);
                    GoodTarget_2 = Form1.GoodTargetIsTrue(Recbuffer_2, bytes_2);
                    Q1_2 = Form1.Q1IsTrue(Recbuffer_2, bytes_2);

                    if (ReceiDataIsTrue_2)
                    {
                        DistanceVale_2 = ReceDataOfDistance(Recbuffer_2, bytes_2);
                        label21.Text = Convert.ToString(GoodTarget_2);
                        label24.Text = Convert.ToString(Q1_2);
                        textBox6.Text = string.Format("{0:F2}", DistanceVale_2);
                        trackBar2.Value = (int)DistanceVale_2;
                        f2 = (double)DistanceVale_2;
                    }
                    else
                    {
                        label21.Text = "null";
                        label24.Text = "null";
                        textBox6.Text = "null";
                        LaserSerialFramDataisErrnumber++;//该帧错误累加1
                    }

                    serial1_send_data(AskLaserDistance_3);
                    System.Threading.Thread.Sleep(30);
                    int bytes_3 = serial1.BytesToRead;
                    byte[] Recbuffer_3 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_3 == 6)
                    {
                        try { serial1.Read(Recbuffer_3, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_3 = new byte[bytes_3];
                        serial1.Read(DiscardBuffer_3, 0, bytes_3);
                    }
                    ReceiDataIsTrue_3 = Form1.ReceDataIsTrue(Recbuffer_3, bytes_3);
                    GoodTarget_3 = Form1.GoodTargetIsTrue(Recbuffer_3, bytes_3);
                    Q1_3 = Form1.Q1IsTrue(Recbuffer_3, bytes_3);

                    if (ReceiDataIsTrue_3)
                    {
                        DistanceVale_3 = ReceDataOfDistance(Recbuffer_3, bytes_3);
                        label22.Text = Convert.ToString(GoodTarget_3);
                        label25.Text = Convert.ToString(Q1_3);
                        textBox7.Text = string.Format("{0:F2}", DistanceVale_3);
                        trackBar3.Value = (int)DistanceVale_3;
                        f3 = (double)DistanceVale_3;
                    }
                    else
                    {
                        label22.Text = "null";
                        label25.Text = "null";
                        textBox7.Text = "null";
                        LaserSerialFramDataisErrnumber++;//该帧错误累加1
                    }

                    serial1_send_data(AskLaserDistance_4);
                    System.Threading.Thread.Sleep(30);
                    int bytes_4 = serial1.BytesToRead;
                    byte[] Recbuffer_4 = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据
                    if (bytes_4 == 6)
                    {
                        try { serial1.Read(Recbuffer_4, 0, 6); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_4 = new byte[bytes_4];
                        serial1.Read(DiscardBuffer_4, 0, bytes_4);
                    }
                    ReceiDataIsTrue_4 = Form1.ReceDataIsTrue(Recbuffer_4, bytes_4);
                    GoodTarget_4 = Form1.GoodTargetIsTrue(Recbuffer_4, bytes_4);
                    Q1_4 = Form1.Q1IsTrue(Recbuffer_4, bytes_4);

                    if (ReceiDataIsTrue_4)
                    {
                        DistanceVale_4 = ReceDataOfDistance(Recbuffer_4, bytes_4);
                        label23.Text = Convert.ToString(GoodTarget_4);
                        label26.Text = Convert.ToString(Q1_4);
                        textBox8.Text = string.Format("{0:F2}", DistanceVale_4);
                        trackBar4.Value = (int)DistanceVale_4;
                        f4 = (double)DistanceVale_4;
                    }
                    else
                    {
                        label23.Text = "null";
                        label26.Text = "null";
                        textBox8.Text = "null";
                        LaserSerialFramDataisErrnumber++;//该帧错误累加1
                    }
                }
                else
                {
                    LaserSerialFramDataisErrnumber++;//该帧错误累加1
                    try
                    {
                        if (comboBox1.Text == "激光测距仪的串口")
                        {

                        }
                        else
                        {
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }

            
            chart1.Series[0].Points.Add(f1);
            chart1.Series[1].Points.Add(f2);
            chart1.Series[2].Points.Add(f3);
            chart1.Series[3].Points.Add(f4);

            if (chart1.Series[0].Points.Count > 20 | chart1.Series[1].Points.Count > 20 | chart1.Series[2].Points.Count > 20 | chart1.Series[3].Points.Count > 20)
            {
                chart1.Series[0].Points.RemoveAt(0);
                chart1.Series[1].Points.RemoveAt(0);
                chart1.Series[2].Points.RemoveAt(0);
                chart1.Series[3].Points.RemoveAt(0);
            }

            if (checkBox2.Checked == true)
            {
                //微气象仪的串口初始化与使用
                byte[] AskWindSpeed_1 = new byte[] { 0xC8, 0x03, 0x00, 0x00, 0x00, 0x01, 0x95, 0x93 }; //C8 03 00 00 00 01 95 93
                byte[] AskWindDirection_1 = new byte[] { 0xC8, 0x03, 0x00, 0x01, 0x00, 0x01, 0xC4, 0x53 }; //C8 03 00 01 00 01 C4 53
                bool ReceiModbusDataIsTrue_1 = false;

                byte[] AskWindSpeed_2 = new byte[] { 0xC9, 0x03, 0x00, 0x00, 0x00, 0x01, 0x94, 0x42 }; //C8 03 00 00 00 01 95 93
                byte[] AskWindDirection_2 = new byte[] { 0xC9, 0x03, 0x00, 0x01, 0x00, 0x01, 0xC5, 0x82 }; //C8 03 00 01 00 01 C4 53
                bool ReceiModbusDataIsTrue_2 = false;


                if (serial2.IsOpen)
                {
                    // serial2.DiscardOutBuffer();
                    // serial2.DiscardInBuffer();
                    serial2_send_data(AskWindSpeed_1);
                    System.Threading.Thread.Sleep(30);
                    int bytes_1 = serial2.BytesToRead;
                    byte[] RecbufferWindSpeed_1 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_1 == 7)
                    {
                        try { serial2.Read(RecbufferWindSpeed_1, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_1 = new byte[bytes_1];
                        serial2.Read(DiscardBuffer_1, 0, bytes_1);
                    }
                    ReceiModbusDataIsTrue_1 = ReceModbusDataIsTrue(RecbufferWindSpeed_1, 7);
                    if (ReceiModbusDataIsTrue_1)
                    {
                        int WindSpeed100_1;
                        WindSpeed100_1 = (RecbufferWindSpeed_1[3] * 256 + RecbufferWindSpeed_1[4]);
                        WindSpeed_1 = WindSpeed100_1 * 0.01;
                        textBox1.Text = string.Format("{0:F2}", WindSpeed_1);
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_1 = false;
                        WinderSerialFramDataisErrnumber++;//该帧错误累加1
                    }

                    serial2_send_data(AskWindDirection_1);
                    System.Threading.Thread.Sleep(30);
                    bytes_1 = serial2.BytesToRead;
                    byte[] RecbufferWindDirection_1 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_1 == 7)
                    {
                        try { serial2.Read(RecbufferWindDirection_1, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_1 = new byte[bytes_1];
                        serial2.Read(DiscardBuffer_1, 0, bytes_1);
                    }
                    ReceiModbusDataIsTrue_1 = ReceModbusDataIsTrue(RecbufferWindDirection_1, 7);
                    if (ReceiModbusDataIsTrue_1)
                    {
                        WindDirection_1 = RecbufferWindDirection_1[3] * 256 + RecbufferWindDirection_1[4];
                        textBox2.Text = WindDirection_1.ToString();
                        if(WindSpeed_1 < 1.00)
                        {
                            //罗盘2静止；

                        }
                        else
                        {
                           Compass_Disp_1(WindDirection_1); //罗盘2更新；
                        }
                        
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_1 = false;
                        WinderSerialFramDataisErrnumber++;//该帧错误累加1
                    }


                    serial2_send_data(AskWindSpeed_2);
                    System.Threading.Thread.Sleep(30);
                    int bytes_2 = serial2.BytesToRead;
                    byte[] RecbufferWindSpeed_2 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_2 == 7)
                    {
                        try { serial2.Read(RecbufferWindSpeed_2, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_2 = new byte[bytes_2];
                        serial2.Read(DiscardBuffer_2, 0, bytes_2);
                    }
                    ReceiModbusDataIsTrue_2 = ReceModbusDataIsTrue(RecbufferWindSpeed_2, 7);
                    if (ReceiModbusDataIsTrue_2)
                    {
                        int WindSpeed100_2;
                        WindSpeed100_2 = (RecbufferWindSpeed_2[3] * 256 + RecbufferWindSpeed_2[4]);
                        WindSpeed_2 = WindSpeed100_2 * 0.01;
                        textBox4.Text = string.Format("{0:F2}", WindSpeed_2);
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_2 = false;
                        WinderSerialFramDataisErrnumber++;//该帧错误累加1
                    }

                    serial2_send_data(AskWindDirection_2);
                    System.Threading.Thread.Sleep(30);
                    bytes_2 = serial2.BytesToRead;
                    byte[] RecbufferWindDirection_2 = new byte[7] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // 声明一个临时数组存储当前来的串口数据风速
                    if (bytes_2 == 7)
                    {
                        try { serial2.Read(RecbufferWindDirection_2, 0, 7); } catch { };
                    }
                    else
                    {
                        byte[] DiscardBuffer_2 = new byte[bytes_2];
                        serial2.Read(DiscardBuffer_2, 0, bytes_2);
                    }
                    ReceiModbusDataIsTrue_2 = ReceModbusDataIsTrue(RecbufferWindDirection_2, 7);
                    if (ReceiModbusDataIsTrue_2)
                    {
                        WindDirection_2 = RecbufferWindDirection_2[3] * 256 + RecbufferWindDirection_2[4];
                        textBox5.Text = WindDirection_2.ToString();
                        if(WindSpeed_2 < 1.00)
                        {
                           //罗盘2静止；
                        }
                        else
                        {
                            Compass_Disp_2(WindDirection_2);//罗盘2更新；
                        }
                        
                    }
                    else
                    {
                        ReceiModbusDataIsTrue_2 = false;
                        WinderSerialFramDataisErrnumber++;//该帧错误累加1
                    }


                }
                else
                {
                    WinderSerialFramDataisErrnumber++;//该帧错误累加1
                    try
                    {
                        if (comboBox2.Text == "微气象仪的串口")
                        {
                        }
                        else
                        {
                        }

                    }
                    catch (Exception ex)
                    {
                        
                    }
                }
            }

            //这里是距离报警点点的颜色改变
            try
            {
                if ((Convert.ToDouble(textBox3.Text) > (Convert.ToDouble(textBox9.Text) + Convert.ToDouble(textBox10.Text))) || (Convert.ToDouble(textBox3.Text) < (Convert.ToDouble(textBox9.Text) - Convert.ToDouble(textBox10.Text))))
                {
                    label33.ForeColor = Color.Red;
                }
                else
                {
                    label33.ForeColor = Color.Green;

                }
                if ((Convert.ToDouble(textBox6.Text) > (Convert.ToDouble(textBox11.Text) + Convert.ToDouble(textBox14.Text))) || (Convert.ToDouble(textBox6.Text) < (Convert.ToDouble(textBox11.Text) - Convert.ToDouble(textBox14.Text))))
                {
                    label34.ForeColor = Color.Red;

                }
                else
                {
                    label34.ForeColor = Color.Green;

                }
                if ((Convert.ToDouble(textBox7.Text) > (Convert.ToDouble(textBox12.Text) + Convert.ToDouble(textBox15.Text))) || (Convert.ToDouble(textBox7.Text) < (Convert.ToDouble(textBox12.Text) - Convert.ToDouble(textBox15.Text))))
                {
                    label35.ForeColor = Color.Red;

                }
                else
                {
                    label35.ForeColor = Color.Green;

                }
                if ((Convert.ToDouble(textBox8.Text) > (Convert.ToDouble(textBox13.Text) + Convert.ToDouble(textBox16.Text))) || (Convert.ToDouble(textBox8.Text) < (Convert.ToDouble(textBox13.Text) - Convert.ToDouble(textBox16.Text))))
                {
                    label36.ForeColor = Color.Red;
                }
                else
                {
                    label36.ForeColor = Color.Green;

                }

            }
            catch (Exception ex)
            {
               
            }

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }
        //****....//private string path = @"C:\Users\Administrator\Desktop\log.csv";//************************************///这里是历史数据保存的地址，随便改啊//************************************//
        
        public void Write()//在CSV表里写一行数据
        {
         string path = System.AppDomain.CurrentDomain.BaseDirectory + "激光测距和微气象仪历史数据/" + "激光测距和微气象仪历史数据" + DateTime.Now.ToString("yyyy" + "年" + "MM" + "月" + "dd" + "日") + ".csv";//"激光测距和微气象仪历史数据.csv";
            if (!File.Exists(path))
                File.Create(path).Close();

            StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
            var time = DateTime.Now.ToString("yyyy" + "年" + "MM" + "月" + "dd" + "日" + "HH" + "时" + "mm" + "分" + "ss" + "秒");
            
                sw.Write( textBox3.Text + ",");//激光1
                sw.Write(textBox6.Text + ",");//激光2
                sw.Write(textBox7.Text + ",");//激光3
                sw.Write(textBox8.Text + ",");//激光4
                sw.Write( textBox1.Text + ",");//风速1
                sw.Write( textBox2.Text + ",");//风向1
                sw.Write(textBox4.Text + ",");//风速2
                sw.Write(textBox5.Text + ",");//风向2
            sw.Write(textBox9.Text + ",");//校准距离1
            sw.Write(textBox11.Text + ",");//校准距离2
            sw.Write(textBox12.Text + ",");//校准距离3
            sw.Write(textBox13.Text + ",");//校准距离4
            sw.Write(textBox10.Text + ",");//阈值1
            sw.Write(textBox14.Text + ",");//阈值2
            sw.Write(textBox15.Text + ",");//阈值3
            sw.Write(textBox16.Text + ",");//阈值4
            sw.Write(time + "\r\n");//数据的日期时间


            sw.Flush();
            sw.Close();
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            Write();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
            
        {

            Properties.Settings.Default.LaserCOMPort = comboBox1.Text;//退出时保存串口配置

            Properties.Settings.Default.WeaCOMPort = comboBox2.Text;
            Properties.Settings.Default.distance1 = textBox9.Text;
            Properties.Settings.Default.distance2 = textBox11.Text;
            Properties.Settings.Default.distance3 = textBox12.Text;
            Properties.Settings.Default.distance4 = textBox13.Text;

            Properties.Settings.Default.Save();

       
            serial1.Close();//退出时释放串口
            serial2.Close();
            Environment.Exit(0);
            Process.GetCurrentProcess().Kill();
        }

        private void CompointBox_Click(object sender, EventArgs e)
        {

        }

        private void label10_Click(object sender, EventArgs e)
        {

        }
        public void HistoryCSVDateShow()//参数读取
        {
            //****//绝对地址// string csvFile = System.IO.Path.Combine(Application.StartupPath, @"C:\Users\Administrator\Desktop\log.csv");//************************************///这里是历史数据保存的地址，随便改啊//************************************//
            //string csvFile = System.IO.Path.Combine(Application.StartupPath, Path.GetFullPath(txtPath.Text));
            txtPath.Text = System.AppDomain.CurrentDomain.BaseDirectory + "激光测距和微气象仪历史数据\\"+"激光测距和微气象仪历史数据" + dateTimePicker1.Text + ".csv";
            string csvFile = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.GetFullPath(txtPath.Text));
            List<string[]> rows = File.ReadAllLines(csvFile).Select(x => x.Split(',')).ToList(); 
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("距离1 mm");
            dataTable.Columns.Add("距离2 mm");
            dataTable.Columns.Add("距离3 mm");
            dataTable.Columns.Add("距离4 mm");
            dataTable.Columns.Add("风速1 m/s"); 
            dataTable.Columns.Add("风向1 °");
            dataTable.Columns.Add("风速2 m/s");
            dataTable.Columns.Add("风向2 °");
            dataTable.Columns.Add("校准距离1");
            dataTable.Columns.Add("校准距离2");
            dataTable.Columns.Add("校准距离3");
            dataTable.Columns.Add("校准距离4");
            dataTable.Columns.Add("阈值1");
            dataTable.Columns.Add("阈值2");
            dataTable.Columns.Add("阈值3");
            dataTable.Columns.Add("阈值4");
            dataTable.Columns.Add("日期");
            dataTable.Columns.Add("备注");
            rows.ForEach(x => { dataTable.Rows.Add(x); });
            dataGridView1.DataSource = dataTable;
            
            long csvSize;
            string filePath = csvFile;
            FileInfo fileInfo = new FileInfo(filePath);
            csvSize = fileInfo.Length /1024;
            /*if (csvSize >= 1024*2)
            {
                MessageBox.Show("历史数据超过2M了，记得及时转移和清理！");
            }*/
            label27.Text = csvSize.ToString();
        }
        public int HistoryDate=0;
        private void button2_Click(object sender, EventArgs e)
        {
            label28.Text = dateTimePicker1.Text + "历史数据KB大小：";
            if (HistoryDate == 0)
            {
                
                HistoryDate = 1;
                try
                { HistoryCSVDateShow();}
                catch 
                { MessageBox.Show("被选日期的历史数据不存在！");
                    DataTable dataTableErr = new DataTable();
                    dataTableErr.Columns.Add("被选日期的历史数据不存在！");
                    dataTableErr.Rows.Add("被选日期的历史数据不存在！");
                    dataGridView1.DataSource = dataTableErr;
                    label27.Text = "文件找不到";
                }
                
                
                
                button2.Text = "关闭数据";
            }
            else
            {
                HistoryDate = 0;
                dataGridView1.DataSource = null;
                dataGridView1.Rows.Clear();
                dataGridView1.Columns.Clear();
                button2.Text = "历史数据";
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_RowErrorTextChanged(object sender, DataGridViewRowEventArgs e)
        {
            
        }

        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void label6_Click_1(object sender, EventArgs e)
        {

        }

        private void label12_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
           
        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "请选择文件夹";
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;
            folderBrowserDialog1.ShowNewFolderButton = true;
            if (txtPath.Text.Length > 0) folderBrowserDialog1.SelectedPath = txtPath.Text;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtPath.Text = folderBrowserDialog1.SelectedPath+ "激光测距和微气象仪历史数据.csv";
            }


        }

        private void txtPath_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void label27_Click(object sender, EventArgs e)
        {

        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        private void txtPath_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            int row = dataGridView1.Rows.Count;//得到总行数   
            string cell_i_j;
            string[] cell_i_jup;
            //int cell = dataGridView1.Rows[1].Cells.Count;//得到总列数   
            for (int i = 0; i < row; i++)//得到总行数并在之内循环   
            {
                int j = 16;
                try
                {
                    cell_i_j = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    cell_i_jup = cell_i_j.Split('时');
                    
                    if (dateTimePicker1.Text + comboBox3.Text == cell_i_jup[0])
                    {   //对比TexBox中的值是否与dataGridView中的值相同（上面这句）   
                        this.dataGridView1.CurrentCell = this.dataGridView1[j, i];//定位到相同的单元格   
                        return;//返回   
                    }
                    else
                    {
                    }
                }
                catch
                {
                    MessageBox.Show("被选时间段的数据不存在！");
                }

            }

        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void label28_Click(object sender, EventArgs e)
        {

        }

        private void label27_Click_1(object sender, EventArgs e)
        {

        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            try { txtPath.Text = System.AppDomain.CurrentDomain.BaseDirectory + "激光测距和微气象仪历史数据\\" + "激光测距和微气象仪历史数据" + dateTimePicker1.Text + ".csv";
            string csvFile = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.GetFullPath(txtPath.Text));
            label28.Text = dateTimePicker1.Text + "历史数据KB大小：";
            long csvSize;
            string filePath = csvFile;
            FileInfo fileInfo = new FileInfo(filePath);
            csvSize = fileInfo.Length / 1024;
            /*if (csvSize >= 1024*2)
            {
                MessageBox.Show("历史数据超过2M了，记得及时转移和清理！");
            }*/
            label27.Text = csvSize.ToString(); 
                Form2 f2 = new Form2(this);
             f2.Show();
        }
           
            catch
            {
                MessageBox.Show("被选日期的历史数据不存在！");
                DataTable dataTableErr = new DataTable();
                dataTableErr.Columns.Add("被选日期的历史数据不存在！");
                dataTableErr.Rows.Add("被选日期的历史数据不存在！");
                dataGridView1.DataSource = dataTableErr;
                label27.Text = "文件找不到";
            }
            
                }

        private void label29_Click(object sender, EventArgs e)
        {

        }

        private void label33_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            textBox9.Text = textBox3.Text;
            textBox11.Text = textBox6.Text;
            textBox12.Text = textBox7.Text;
            textBox13.Text = textBox8.Text;

            button6.Text = "已校";
        }
        private void textBox9_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox11_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox12_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox13_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox10_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox14_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox15_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox16_TextChanged(object sender, EventArgs e)
        {

        }

        private void label34_Click(object sender, EventArgs e)
        {

        }

        private void label35_Click(object sender, EventArgs e)
        {

        }

        private void label36_Click(object sender, EventArgs e)
        {

        }

        private void label25_Click(object sender, EventArgs e)
        {

        }

        private void label37_Click(object sender, EventArgs e)
        {

        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void trackBar2_Scroll(object sender, EventArgs e)
        {

        }
    }
    public static class CRC16
    {
        /// <summary>
        /// CRC校验，参数data为byte数组
        /// </summary>
        /// <param name="data">校验数据，字节数组</param>
        /// <returns>字节0是高8位，字节1是低8位</returns>
        public static byte[] CRCCalc(byte[] data)
        {
            //crc计算赋初始值
            int crc = 0xffff;
            for (int i = 0; i < data.Length; i++)
            {
                crc = crc ^ data[i];
                for (int j = 0; j < 8; j++)
                {
                    int temp;
                    temp = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (temp == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }
            }
            //CRC寄存器的高低位进行互换
            byte[] crc16 = new byte[2];
            //CRC寄存器的高8位变成低8位，
            crc16[1] = (byte)((crc >> 8) & 0xff);
            //CRC寄存器的低8位变成高8位
            crc16[0] = (byte)(crc & 0xff);
            return crc16;
        }

        /// <summary>
        /// CRC校验，参数为空格或逗号间隔的字符串
        /// </summary>
        /// <param name="data">校验数据，逗号或空格间隔的16进制字符串(带有0x或0X也可以),逗号与空格不能混用</param>
        /// <returns>字节0是高8位，字节1是低8位</returns>
        public static byte[] CRCCalc(string data)
        {
            //分隔符是空格还是逗号进行分类，并去除输入字符串中的多余空格
            IEnumerable<string> datac = data.Contains(",") ? data.Replace(" ", "").Replace("0x", "").Replace("0X", "").Trim().Split(',') : data.Replace("0x", "").Replace("0X", "").Split(' ').ToList().Where(u => u != "");
            List<byte> bytedata = new List<byte>();
            foreach (string str in datac)
            {
                bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier));
            }
            byte[] crcbuf = bytedata.ToArray();
            //crc计算赋初始值
            return CRCCalc(crcbuf);
        }

        /// <summary>
        ///  CRC校验，截取data中的一段进行CRC16校验
        /// </summary>
        /// <param name="data">校验数据，字节数组</param>
        /// <param name="offset">从头开始偏移几个byte</param>
        /// <param name="length">偏移后取几个字节byte</param>
        /// <returns>字节0是高8位，字节1是低8位</returns>
        public static byte[] CRCCalc(byte[] data, int offset, int length)
        {
            byte[] Tdata = data.Skip(offset).Take(length).ToArray();
            return CRCCalc(Tdata);
        }
    }
}
